<template>
  <!-- 加载状态 -->
  <div v-if="isLoading" class="loadingContainer">
    <a-spin size="large" tip="正在加载数据...">
      <div class="loadingContent"></div>
    </a-spin>
  </div>
  
  <!-- 主界面 -->
  <a-layout
    v-else
    class="layoutContainer themeDark"
    style="height: 100vh; overflow: hidden"
  >
    <a-layout-header class="header">
      <div class="logoContent">
        <div class="logo" />
      </div>
      <div class="headerMiddle">
        <MenuUnfoldOutlined
          v-if="collapsed"
          class="trigger"
          @click="() => (collapsed = !collapsed)"
        />
        <MenuFoldOutlined
          v-else
          class="trigger"
          @click="() => (collapsed = !collapsed)"
        />
        <a-breadcrumb style="margin: 0 15px 0 15px">
          <a-breadcrumb-item>广东新巨能能源科技有限公司</a-breadcrumb-item>
          <a-breadcrumb-item v-for="item in breadcrumb" :key="item">{{
            item
          }}</a-breadcrumb-item>
        </a-breadcrumb>
        <div class="userInf">
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              你好，{{
                userInf?.baseUser?.username || userId?.user_info?.uname
              }}
              <CaretDownOutlined class="arrow-icon" />
              <CaretUpOutlined class="arrow-icon arrow-up" />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="changePassword">
                  <LockOutlined />
                  修改密码
                </a-menu-item>
                <a-menu-item key="2" @click="handleLogout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>
    <a-layout style="height: calc(100vh - 64px); overflow: hidden">
      <a-layout-sider
        v-model:collapsed="collapsed"
        :trigger="null"
        width="200"
        style="background: #001529; height: 100%; overflow-y: auto"
      >
        <a-menu
          v-model:selectedKeys="selectedKeys"
          v-model:openKeys="openKeys"
          theme="dark"
          mode="inline"
          :style="{ height: '100%', borderRight: 0 }"
          :items="menuList"
          @click="handleClickMenu"
        >
          <template #icon="{ icon }">
            <ItalicOutlined />
          </template>
        </a-menu>
      </a-layout-sider>
      <a-layout class="layout" style="overflow-y: auto">
        <a-layout-content
          :style="{
            margin: 0,
            minHeight: 'calc(100vh - 64px - 48px)',
          }"
          class="layoutContent"
        >
          <Tags :menuList="menuList" />
          <div
            :style="{ padding: '12px 17px 17px', background: bgColor }"
            class="content"
          >
            <router-view v-if="hasPermission" />
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </a-layout>

  <ChangePassword
    v-model:changePasswordVisible="changePasswordVisible"
    :userId="userId?.user_id"
    :force="isForce"
  />
</template>

<script setup>
import Tags from "./conpoments/tags.vue"
import ChangePassword from "./conpoments/changePassword.vue"
const router = useRouter()
import * as AntIcons from "@ant-design/icons-vue"
import { useLoginStore } from "@/stores/loginConfig"
import { useUserStore } from "@/stores/user"

const { changeLoginData } = useLoginStore()
import storage from "@/utils/storage"
import pinia from "@/stores/store"

const systemDataStore = useLoginStore(pinia)
const userStore = useUserStore(pinia)
const $api = inject("$api")
const selectedKeys = ref([])
const openKeys = ref([])
const breadcrumb = ref([])
const collapsed = ref(false)
const menuList = ref([])

const changePasswordVisible = ref(false)
const isForce = ref(false)
const userId = storage.getItem("USER_INFO")
const userInf = ref({})
//获取当前路由设置背景颜色
const bgColor = computed(() => {
  const route = router.currentRoute.value

  if (route.name === "StationOverview") {
    return "#162634"
  } else {
    return ""
  }
  return route.name
})
//修改密码
const changePassword = async () => {
  isForce.value = false
  changePasswordVisible.value = true
}
// 获取用户信息
const getUserInf = async () => {
  if (!userId) return null
  const res = await $api.queryUserInfo({
    userId: userId?.user_id,
  })
  if (res?.code === 0) {
    userInf.value = res.data
  }
  return res
}
//判断是否强制更改密码
const getForceChangePassword = async (id) => {
  try {
    const res = await $api.forceUpdatePwd(id)
    if (res && res.code === 0) {
      if (res.data.value === 1) {
        changePasswordVisible.value = true
        isForce.value = true
      }
    }
  } catch (error) {
    console.error("表单验证失败:", error)
  }
}
const extractTitles = (menu, keys) => {
  let titles = []
  const findTitles = (menuItem, keys) => {
    if (keys.includes(menuItem.key)) {
      titles.push(menuItem.title)
    }
    if (menuItem.children) {
      for (const child of menuItem.children) {
        findTitles(child, keys)
      }
    }
  }
  for (const item of menu) {
    findTitles(item, keys)
  }
  return titles
}

// 新增状态控制
const isLoading = ref(true)
const hasPermission = ref(false)

// 扁平化菜单列表的辅助函数
const flattenMenuList = (list) => {
  return list.reduce((acc, cur) => {
    const items = [cur]
    if (cur.children) {
      items.push(...flattenMenuList(cur.children))
    }
    return acc.concat(items)
  }, [])
}

// 检查当前页面权限
const checkCurrentPagePermission = (currentPath) => {
  const whiteList = ['/login', '/permission/NoPermission', '/', '/DataScreen/StorageAndSale', '/DataScreen/StorageCharging']
  // 白名单直接通过
  if (whiteList.includes(currentPath) || whiteList.includes(router.currentRoute.value.path)) {
    return true
  }
  // 检查菜单权限
  if (Array.isArray(userStore.menuData)) {
    const flattenedMenuList = flattenMenuList(userStore.menuData);
    const hasAccess = flattenedMenuList.some(item => 
      item.path === currentPath || item.path === router.currentRoute.value.path
    )
    return hasAccess
  }
  return false
}

// 初始化应用数据
const initializeApp = async () => {
  try {
    isLoading.value = true
    // 检查登录状态
    if (!userId) {
      router.push("/login")
      return
    }
    // 获取用户信息和菜单数据
    const userRes = await userStore.fetchUserData(userId?.user_id)
    if (userRes) {
      await userStore.fetchMenuData(userRes?.roles)
      // 检查当前页面权限
      const currentPath = router.currentRoute.value.fullPath
      const hasAccess = checkCurrentPagePermission(currentPath)
      if (hasAccess) {
        hasPermission.value = true
      } else {
        // 没有权限，跳转到无权限页面
        router.replace({ path: '/permission/NoPermission' })
        return
      }
    }
    // 检查是否需要强制修改密码
    await getForceChangePassword(userId?.user_id)
  } catch (error) {
    // 出错时跳转到登录页
    router.push("/login")
  } finally {
    isLoading.value = false
  }
}

watch(
  () => [router.currentRoute.value, menuList.value],
  ([val, menuListVal]) => {
    // 监听当前路由，设置选中的菜单
    selectedKeys.value = [val.name]
    openKeys.value = val.path.replace(/^\/|\/$/g, "").split("/") // 去掉path的斜杠
    breadcrumb.value = extractTitles(menuList.value, openKeys.value) // 根据openKeys.value的值，获取对应的面包屑title
  },
  { immediate: true }
)

const handleClickMenu = (e) => {
  router.push(e.item.path)
  selectedKeys.value = [e.key]
}

// const getButtonIds = (array) => {
//   // 递归获取按钮权限key
//   let buttonIds = []
//   function traverse(node) {
//     if (node.btnList && node.btnList.length > 0) {
//       buttonIds.push(...node.btnList.map((btn) => btn.permission))
//     }
//     if (node.children && node.children.length > 0) {
//       node.children.forEach((child) => traverse(child))
//     }
//   }
//   array.forEach((item) => traverse(item))
//   return buttonIds
// }

const getBaseMenuList = async (list) => {
  /* const parmas = {
    menuType: MENU_AUTH.menu,
    roleIds:
      Object.keys(userInf.value).length > 0
        ? userInf.value?.roles.join(",")
        : "",
  }
  const res = await $api.baseMenuList(parmas)

  if (res && res.code === 0) {
   
  } */

  if (list.length > 0) {
    systemDataStore.changeMenuData(list)
    menuList.value = list
    const addNameField = (menu) => {
      menu.forEach((item) => {
        // 给当前菜单项添加 name 字段
        item.title = item.name
        item.label = item.name
        item.permission = item.permission
        item.key = item.path?.split("/").pop()
        const icon = item.icon
        // <component :is="menu.icon"/>
        item.icon = () => h(AntIcons[icon])
        // 如果有子菜单项
        if (item.children && item.children.length > 0) {
          addNameField(item.children)
        }
      })
    }
    // 使用递归函数来更新 menuList
    addNameField(menuList.value)
  }
}
watch(
  () => userStore.menuData,
  (val) => {
    if (val) {
      getBaseMenuList(val)
    }
  },
  { immediate: true }
)

// 监听路由，检查权限
watch(() => router.currentRoute.value, (newRoute) => {
  if (!isLoading.value && userStore.menuData) {
    const hasAccess = checkCurrentPagePermission(newRoute.fullPath)
    if (!hasAccess) {
      router.replace({ path: '/permission/NoPermission' })
    } else {
      hasPermission.value = true
    }
  }
}, { immediate: false })

onMounted(async () => {
  await initializeApp()
})
const handleLogout = async () => {
  const res = await $api.logout()
  if (res?.code === 0) {
    // 清除用户信息
    storage.clearItem("USER_INFO")
    // 清除系统状态
    changeLoginData({})
    // 清除菜单数据和用户信息
    userStore.logout()
    // 跳转到登录页
    router.push("/login")
  }
}
</script>
<style lang="less" scoped>
@layoutBackground: #2b2b2b;
.themeDark {
  .layout {
    background-color: @layoutBackground;
  }
}
.header {
  position: relative;
}
.content {
  min-height: calc(100vh - 100px);
}
.logoContent {
  display: inline-block;
  .title {
    display: inline-block;
    font-size: 18px;
    font-weight: bold;
    position: relative;
    left: 5px;
    top: 5px;
  }
}
.logo {
  width: 140px;
  height: 62px;
  background: url(/src/assets/logo.png) no-repeat center center;
  background-size: contain;
  display: inline-block;
  vertical-align: middle;
  position: relative;
  bottom: 5px;
  right: 18px;
}
.headerMiddle {
  position: absolute;
  top: 0;
  left: 200px;
  display: flex;
  align-items: center;
  width: calc(100% - 200px);
  .userInf {
    margin-left: auto;
    margin-right: 20px;
    display: flex;
    align-items: center;
    .messageIcon {
      font-size: 16px;
      margin-right: 20px;
      cursor: pointer;
    }
    .ant-dropdown-link {
      color: #fff;
      display: flex;
      align-items: center;
      .arrow-icon {
        margin-left: 5px;
        transition: transform 0.3s ease;
      }
      .arrow-up {
        display: none;
      }
      &:hover {
        .arrow-icon {
          transform: rotate(180deg);
        }
      }
    }
  }
}
.ant-breadcrumb {
  display: inline-block;
}

.loadingContainer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #2b2b2b;
  
  .loadingContent {
    width: 200px;
    height: 100px;
  }
  :deep(.ant-spin) {
    background: #2b2b2b;
  }
}
</style>
<style lang="less">
.filterContent {
  background: #141414;
  margin-bottom: 20px;
  padding: 20px 20px 0 20px;
  border-radius: 4px;
  .ant-form-item {
    margin-bottom: 20px;
  }
}
// 警告按钮
@yellow: #a77730;
.yellowBtn {
  background-color: orange;
  color: white;
  &:hover {
    background-color: @yellow !important;
    border-color: @yellow !important;
    color: #fff !important;
  }
}
// 绿色按钮
@green: #529b2e;
.greenBtn {
  background-color: green;
  color: white;
  &:hover {
    background-color: @green !important;
    border-color: @green !important;
    color: #fff !important;
  }
}
//绿色半透明按钮
.greenpPlainBtn {
  background-color: rgba(0, 128, 0, 0.2) !important;
  color: greenyellow;
  border-color: greenyellow;
  &:hover {
    background-color: rgba(0, 128, 0, 0.2) !important;
    border-color: greenyellow !important;
    color: greenyellow !important;
  }
}
//蓝色半透明按钮
@blue: #409eff;
.bluePlainBtn {
  background-color: rgba(22, 85, 173, 0.2) !important;
  color: @blue;
  border-color: @blue;
  &:hover {
    background-color: rgba(22, 85, 173, 0.2) !important;
    border-color: rgb(22, 85, 173, 0.2) !important;
    color: @blue !important;
  }
}
</style>
